<template>
	<view class="fun-circle-box" v-if="!InterfaceException">
		<scroll-view class="scroll-view-box" scroll-y="true" :scroll-top="scrollTop" @scroll="handleScroll"
			@scrolltolower="loadMore">
			<view class="content-box-item" v-for="(item, index) in funCircleList" :key="item">
				<view class="landlord-info-box">
					<view class="left-info">
						<image class="landlord-head-src" :src="item.headSrc"></image>
						<view class="landlord-user-name">{{ item.userName }}</view>
					</view>
					<view class="right-follow-with-interest">
						<block v-if="userInfo.id != item.userId">
							<up-button size="mini" :color="item.concernStatus? '#ccc' : '#df2123'" type="primary"
								:text="item.concernStatus? '已关注' : '+ 关注'"
								@click="handleConcern(item, index)"></up-button>


							<view style="margin-left: 12rpx;">
								<up-button size="mini" :color="item.collectStatus? '#fd6200' : ''" type="primary"
									:text="item.collectStatus? '已收藏' : '收藏'"
									@click="handleCollect(item, index)"></up-button>
							</view>
						</block>
					</view>
				</view>

				<view class="landlord-content">{{ item.content }}</view>

				<view class="landlord-img-box" v-if="item.images && item.images.length > 0">
					<block v-if="item.images.length == 1">
						<OneRowOneVue :imageSrcList="item.images" />
					</block>

					<block v-else-if="item.images.length == 2 || item.images.length == 4">
						<OneRowTwoVue :imageSrcList="item.images" />
					</block>

					<block v-else>
						<OneRowThreeVue :imageSrcList="item.images" />
					</block>
				</view>

				<view class="like-the-highest-box" v-if="item.likeTheHighest">
					<view class="top-info-box">
						<view class="user-info">
							<image class="like-the-highest-head-src" :src="item.likeTheHighest.headSrc" />
							<view class="like-the-highest-head-user-name">{{ item.likeTheHighest.userName }}</view>
						</view>
						<view class="like-count">
							<text
								style="margin-right: 8rpx; font-size: 24rpx;">{{ item.likeTheHighest.totalLikes }}</text>
							<u-icon size="24px" :color="item.likeTheHighest.likeStatus? 'red' : '#606266'"
								:name="item.likeTheHighest.likeStatus? 'thumb-up-fill' : 'thumb-up'"
								@click="handleLikeTheHighestLike(item, index)" />
						</view>
					</view>
					<view class="bottom-content-box">{{ item.likeTheHighest.content }}</view>
				</view>

				<view class="data-info-box">
					<view class="item-box">
						<up-icon size="24px" :color="item.likeStatus? 'red' : '#606266'"
							:name="item.likeStatus? 'thumb-up-fill' : 'thumb-up'"
							@click="handleLikeOfStep(item, index, 1)" />
						<text>{{ item.totalLikes }}</text>
					</view>
					<view class="item-box">
						<up-icon size="24px" :color="item.stepStatus? 'red' : '#606266'"
							:name="item.stepStatus? 'thumb-down-fill' : 'thumb-down'"
							@click="handleLikeOfStep(item, index, 2)" />
						<text>{{ item.totalStepOns }}</text>
					</view>
					<view class="item-box">
						<up-icon size="24px" name="chat" @click="handleComment(item, index)" />
						<text>{{ item.totalComments }}</text>
					</view>
					<view class="item-box">
						<up-icon size="24px" name="share-square" @click="handleShare(item, index)" />
						<text>{{ item.totalForwards }}</text>
					</view>
				</view>
			</view>

			<view v-if="outTextFlag" class="out-text">已经到底了</view>
		</scroll-view>

		<view class="back-to-top" v-if="scrollTopFlag" @click="backToTop">
			<up-icon name="arrow-upward" color="#000" size="14" />
			<text>顶部</text>
		</view>

		<view class="back-to-top" v-else @click="onRefresh">
			<up-icon name="reload" color="#000" size="14" />
			<text>刷新</text>
		</view>

		<!-- 评论弹窗 -->
		<PopupVue ref="childPopupRef" :popupShow="popupShow" :currentUserId="userInfo.id" @closeCB="onClose" />

	</view>

	<div class="fun-circle-box2" v-else>
		<up-empty mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png">
		</up-empty>
	</div>

</template>

<script setup lang="ts">
	import OneRowOneVue from '../layoutComponents/oneRowOne.vue';
	import OneRowTwoVue from '../layoutComponents/OneRowTwo.vue';
	import OneRowThreeVue from '../layoutComponents/OneRowThree.vue';
	import PopupVue from '../popupComponents/index.vue';
	import { getFunCircleApi, currencyCountApi, commentsCurrencyCountApi, concernOrCancelApi } from '@/api/funCircleApi.js';
	import { getOpenIdApi } from '@/api/my.js';
	import { throttle, isUniqueArray } from '@/utils/common.js'

	import { defineProps, ref, onMounted } from 'vue';
	const props = defineProps({
		tabsId: String || null
	});

	// 引入组件
	components: {
		OneRowOneVue;
		OneRowTwoVue;
		OneRowThreeVue;
		PopupVue
	};

	// 当前登录的用户信息
	const userInfo = ref(null)
	//兜底状态
	const InterfaceException = ref(true)

	// 弹窗状态
	const childPopupRef = ref(null)
	const popupShow = ref(false)

	// 趣事圈数据格式
	const funCircleList = ref([]);

	// 顶部距离
	const scrollTop = ref(1)
	const scrollTopFlag = ref(false) // 小程序特定此字段来控制

	const id = ref(null) // tab下面的某一条数据的id
	const dataIndex = ref(null) // 哪条数据的下标
	// 当前tab的页码  
	const totalPages = ref(0)
	const currentPage = ref(1);
	const pageSize = 10; // 公共

	// 到底文案
	const outTextFlag = ref(false)

	// handleScroll 方法来更新 scrollTop 的值  
	const handleScroll = (e) => {
		// 监听滚动事件，e.detail.scrollTop是滚动条距离顶部的距离  
		if (e.detail.scrollTop > 300) { // 滚动超过300px时显示返回顶部按钮  
			// scrollTop.value = e.detail.scrollTop;
			scrollTopFlag.value = true
		} else {
			scrollTop.value = 1;
			scrollTopFlag.value = false
		}
	}

	// 返回顶部事件
	const backToTop = () => {
		if (scrollTopFlag.value) {
			scrollTop.value = 0
			// let currentScrollTop : any = scrollTop.value;
			// const step = currentScrollTop / 10; // 分步滚动  
			// const timer = setInterval(() => {
			// 	if (currentScrollTop > 0) {
			// 		currentScrollTop -= step;
			// 		scrollTop.value = currentScrollTop;
			// 	} else {
			// 		clearInterval(timer);
			// 		scrollTop.value = 0
			// 	}
			// }, 50); // 每50ms执行一次  
		}
	}

	// 组件一进来触发
	onMounted(async () => {
		if (uni.getStorageSync('userInfo') == '') {
			const loginRes = await uni.login({
				provider: 'weixin',
			});
			if (loginRes && loginRes.code) {
				let { code, errorMsg, results } = await getOpenIdApi({
					code: loginRes.code
				})
				if (code == 200) {
					uni.setStorageSync('userInfo', results)
					userInfo.value = results
					// 获取趣事圈列表数据
					await getFunCircle(currentPage.value)
				} else {
					console.log('errorMsg', errorMsg)
				}
			}
		} else {
			userInfo.value = uni.getStorageSync('userInfo')
			// 获取趣事圈列表数据
			await getFunCircle(currentPage.value)
		}
	})

	// 刷新
	const onRefresh = async () => {
		await getFunCircle(currentPage.value)
	}

	// 分页上拉加载
	const loadMore = async () => {
		let isLoadMore = totalPages.value > currentPage.value
		if (!isLoadMore) return outTextFlag.value = true
		currentPage.value = ++currentPage.value
		await getFunCircle(currentPage.value)
	}

	// 封装获取趣事圈接口数据
	const getFunCircle = async (currentPage : any) => {
		await getFunCircleApi({
			currentPage: currentPage,
			pageSize: pageSize,
			currentUserId: userInfo.value.id
		}).then(res => {
			if (res && res.code == 200) {
				InterfaceException.value = false
				let { records, total } = res.results
				funCircleList.value = isUniqueArray(funCircleList.value, records)
				totalPages.value = Math.ceil(total / pageSize)
			} else {
				InterfaceException.value = true
				errTips()
			}
		}).catch(err => {
			InterfaceException.value = true
			errTips()
		})
	}

	// 点击评论
	const handleComment = async (item, index) => {
		id.value = item.id
		dataIndex.value = index + 1
		popupShow.value = true
		childPopupRef.value.getCommentData(item.id)
	}

	const onClose = async () => {
		popupShow.value = false;
		if (dataIndex.value >= 0) {
			await getFunCircleApi({
				currentPage: dataIndex.value,
				pageSize: 1,
				currentUserId: userInfo.value.id
			}).then(res => {
				if (res && res.code == 200) {
					InterfaceException.value = false
					let { records } = res.results
					funCircleList.value[dataIndex.value - 1] = records[0]
				} else {
					InterfaceException.value = true
					errTips()
				}
			}).catch(err => {
				InterfaceException.value = true
				errTips()
			})
		} else {
			await getFunCircle(currentPage.value)
		}
	}

	// 点收藏操作 - 回显界面
	const handleCollect = throttle(async (item, index) => {
		await currencyCount(item, 3, index)
	}, 2000)

	// 点关注操作 - 回显界面
	const handleConcern = throttle(async (item, index) => {
		let { code } = await concernOrCancelApi({
			currentUserId: userInfo.value.id,
			type: !item.concernStatus,
			userId: item.userId
		})
		if (code == 200 || code == 0) {
			funCircleList.value[index].concernStatus = !item.concernStatus
			successTips()
		} else {
			errTips()
		}
	}, 2000)

	// 最高点赞 - 点赞操作 - 回显界面
	const handleLikeTheHighestLike = throttle(async (item, index) => {
		// 调评论的点赞
		await commentsCurrencyCountApi(
			{
				flag: !item.likeTheHighest.likeStatus,
				graphicCommentsId: item.likeTheHighest.id,
				type: 1,
				currentUserId: userInfo.value.id
			}
		).then(res => {
			funCircleList.value[index].likeTheHighest.likeStatus = !item.likeTheHighest.likeStatus
			if (!item.likeTheHighest.likeStatus) {
				funCircleList.value[index].likeTheHighest.totalLikes = --item.likeTheHighest.totalLikes
			} else {
				funCircleList.value[index].likeTheHighest.totalLikes = ++item.likeTheHighest.totalLikes
			}
			successTips()
		}).catch(err => {
			errTips()
		})
	}, 2000)

	// 点赞操作 / 踩 - 回显界面
	const handleLikeOfStep = throttle(async (item, index, type) => {
		if (type === 1) {//点了赞
			if (!item.likeStatus && item.stepStatus && item.totalStepOns > 0) {
				funCircleList.value[index].stepStatus = false
				funCircleList.value[index].totalStepOns = --item.totalStepOns
			}

		} else {//点了踩
			if (!item.stepStatus && item.likeStatus && item.totalLikes > 0) {
				funCircleList.value[index].likeStatus = false
				funCircleList.value[index].totalLikes = --item.totalLikes
			}
		}
		await currencyCount(item, type, index)
	}, 2000)

	// 分享操作 - 回显界面
	const handleShare : any = throttle(async (item, index) => {
		funCircleList.value[index].totalForwards = ++item.totalForwards;

		(uni as any).showShareMenu({
			path: '/pages/home/index', // 分享链接，该路径必须是可以被微信解析的链接  
			success: function (res) {
				// 转发成功  
				uni.showToast({ title: '转发成功', icon: 'success' });
				currencyCount(item, 4, index)
			},
			fail: function (err) {
				// 转发失败  
				uni.showToast({ title: '转发失败', icon: 'none' });
			}
		});
	}, 2000)

	// 封装点赞 、踩、收藏、转发趣事圈接口数据
	const currencyCount = async (item, type, index) => {
		await currencyCountApi({
			flag: type == 1 ? !item.likeStatus : type == 2 ? !item.stepStatus : type == 3 ? !item.collectStatus : true,
			graphicId: item.id,
			type,
			currentUserId: userInfo.value.id
		}).then(res => {
			if (res && res.code == 200) {
				if (type == 1) {
					funCircleList.value[index].likeStatus = !item.likeStatus
					if (!item.likeStatus) {
						funCircleList.value[index].totalLikes = --item.totalLikes
					} else {
						funCircleList.value[index].totalLikes = ++item.totalLikes
					}
				}
				if (type == 2) {
					funCircleList.value[index].stepStatus = !item.stepStatus
					if (!item.stepStatus) {
						funCircleList.value[index].totalStepOns = --item.totalStepOns
					} else {
						funCircleList.value[index].totalStepOns = ++item.totalStepOns
					}
				}
				if (type == 3) {
					funCircleList.value[index].collectStatus = !item.collectStatus
				}
				successTips()
			} else {
				errTips()
			}
		})
	}

	// 成功提示
	const successTips = () => {
		uni.showToast({ title: '操作成功', icon: 'success' });
	}

	// 异常提示
	const errTips = () => {
		uni.showToast({ title: '操作异常', icon: 'error' });
	}
</script>

<style lang="scss" scoped>
	.fun-circle-box2 {
		width: 100%;
		height: calc(100vh - 100rpx);
	}

	.fun-circle-box {
		width: 100%;

		.scroll-view-box {
			width: 100%;
			height: calc(100vh - 100rpx);
			// margin-top: 100rpx;

			.content-box-item {
				padding: 24rpx;
				margin-bottom: 12px;
				background-color: #fff;

				.landlord-info-box {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.left-info {
						display: flex;
						align-items: center;

						.landlord-head-src {
							width: 88rpx;
							height: 88rpx;
							border-radius: 50%;
						}

						.landlord-user-name {
							width: calc(100% - 88rpx - 24rpx);
							margin-left: 24rpx;
							font-weight: 700;
						}
					}

					.right-follow-with-interest {
						display: flex;
					}
				}

				.landlord-content {
					margin-top: 12rpx;
					width: 100%;
					padding: 0 24rpx;
					box-sizing: border-box;
				}

				.landlord-img-box {
					margin-top: 12rpx;
					width: 100%;
					padding: 0 24rpx;
					box-sizing: border-box;
				}

				.like-the-highest-box {
					width: 100%;
					border-radius: 16rpx;
					background-color: #f9f9f9;
					padding: 24rpx 16rpx;
					box-sizing: border-box;
					margin-top: 12rpx;

					.top-info-box {
						width: 100%;
						display: flex;
						justify-content: space-between;
						align-items: center;

						.user-info {
							display: flex;
							align-items: center;

							.like-the-highest-head-src {
								width: 88rpx;
								height: 88rpx;
								border-radius: 50%;
							}

							.like-the-highest-head-user-name {
								margin-left: 16rpx;
								font-size: 28rpx;
							}
						}

						.like-count {
							display: flex;
							align-items: center;
						}
					}

					.bottom-content-box {
						margin-top: 24rpx;
						font-size: 28rpx;
					}
				}

				.data-info-box {
					width: 100%;
					padding: 0 24rpx;
					box-sizing: border-box;
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: 24rpx;

					.item-box {
						display: flex;
						align-items: center;

						text {
							font-size: 24rpx;
							margin-left: 8rpx;
						}
					}
				}

			}

			.content-box-item:last-child {
				margin-bottom: 0 !important;
			}

			.out-text {
				display: flex;
				align-items: center;
				justify-content: center;
				color: #ccc;
				padding-bottom: 12px;
				box-sizing: border-box;
			}
		}

		.back-to-top {
			position: fixed;
			bottom: 100px;
			right: 20px;
			display: flex;
			align-items: center;
			justify-content: center;
			width: 88rpx;
			height: 88rpx;
			border-radius: 50%;
			background-color: #fff;
			color: #000;
			font-size: 20rpx;
			box-shadow: 0rpx 0rpx 8rpx 8rpx rgb(0, 0, 0, 0.1);
			font-weight: 700;
		}

	}
</style>